package com.example.util;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpUtil {
	
	private static String TAG = "HttpUtil";

	public static String doPost(String url, List<NameValuePair> params){
		if(null != url && url.trim().length() > 0) {
			Log.i(TAG, url);
			HttpPost httpRequest = new HttpPost(url);  
			try {
				if(null != params) {
					/* 添加请求参数到请求对象 */
					httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				}
				/* 发送请求并等待响应 */
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpRequest);
				/* 若状态码为200 ok */
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					/* 读返回数据 */
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());
					Log.i(TAG, strResult);
					return strResult;
				} else {
					Log.i("doPost", "請求" + url + "失败！");
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
